package cn.yedong.user.service.impl;

import cn.yedong.basic.exception.BusinessException;
import cn.yedong.basic.service.Impl.BaseServiceImpl;
import cn.yedong.basic.util.Md5Utils;
import cn.yedong.basic.util.StrUtils;
import cn.yedong.user.domain.Logininfo;
import cn.yedong.user.domain.User;
import cn.yedong.user.mapper.LogininfoMapper;
import cn.yedong.user.mapper.UserMapper;
import cn.yedong.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 同步修改登陆信息：添加
     * 添加用户之前要先添加logininfo，获取logininfo自增id设置给user，再添加user
     * @param user
     */
    @Override
    @Transactional
    public void add(User user) {
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //添加Logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);//用户注册
        logininfo.setDisable(true);//管理员后台直接添加，默认为true
        logininfoMapper.add(logininfo);//产生自增id

        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    /**
     * 同步修改登陆信息：删除
     * 删除user之前先删除logininfo
     * @param id
     */
    @Override
    @Transactional
    public void del(Long id) {
        Long dbLogininfoId = userMapper.loadById(id).getLogininfoId();
        logininfoMapper.del(dbLogininfoId);
        super.del(id);
    }

    /**
     * 同步修改登录信息：修改
     * 修改user之前先修改dbLogininfo
     * @param user
     */
    @Override
    @Transactional
    public void update(User user) {
        //先查询数据库中User和Logininfo
        User dbUser = userMapper.loadById(user.getId());
        Logininfo dbLogininfo = logininfoMapper.loadById(dbUser.getId());

        if(!user.getPassword().equals(dbUser.getPassword())){
            //获取盐值
            String salt = StrUtils.getComplexRandomString(32);
            //加密加盐
            String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
            user.setSalt(salt);
            user.setPassword(md5Pwd);
        }

        BeanUtils.copyProperties(user,dbLogininfo);
        //注意，此时dbLogininfo的id会被userid覆盖
        dbLogininfo.setId(dbUser.getLogininfoId());
//        dbLogininfo.setType(1);//type不会被覆盖；也不需要更新
        //根据修改的user状态来设置登陆信息状态
        if(user.getState() == 1){
            dbLogininfo.setDisable(true);
        }else{
            dbLogininfo.setDisable(false);
        }
        //管理员后台直接，默认为true
        super.update(user);
    }

    /**
     * 同步登录信息：批量删除
     * @param ids
     */
    @Override
    public void patchDel(List<Long> ids) {
        for (Long id : ids) {
            del(id);
        }
    }

    /**
     * 手机号码注册
     * @param map
     */
    @Override
    @Transactional
    public void phoneRegister(Map<String, String> map) {
        String phoneCode = map.get("imageCode");
        String phone = map.get("phone");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //1.空值校验
        if(StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(phone) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空！");
        }
        //2.密码校验
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致！");
        }
        //3.验证码过期校验
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj == null){
            throw new BusinessException("手机验证码已过期！");
        }
        //4.验证码校验
        if(!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误！");
        }

        //存入数据库
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /**
     * 邮箱注册
     * @param map
     */
    @Override
    @Transactional
    public void mailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //1.空值校验
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空！");
        }
        //2.重复注册校验
        User dbUser = userMapper.findByEmail(email);
        if(dbUser != null){
            throw new BusinessException("账号已注册，如果忘记密码，请联系管理员！");
        }
        //3.密码校验
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一样！");
        }
        //4.存入数据库
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
        //5.发送激活邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        messageHelper.setFrom("974431480@qq.com");
        messageHelper.setSubject("【宠物之家】注册成功通知！");
        Long userId = user.getId();
        messageHelper.setText("邮箱是"+email+"的用户您好,恭喜您成为【宠物之家】会员，请<a href='http://localhost:8080/user/register/mailActive/"+userId+"'>点击该链接</a>"+"激活账户！",true);
        messageHelper.setTo(email);
        javaMailSender.send(mimeMessage);

    }

    /**
     * 邮箱注册-激活
     * @param id
     */
    @Override
    @Transactional
    public void mailActive(Long id) {
        User user = userMapper.loadById(id);
        user.setState(1);//启用
        userMapper.update(user);
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        logininfo.setDisable(true);
        logininfoMapper.update(logininfo);
    }

    /**
     * 将user对象拷贝至logininfo对象
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //根据属性同名原则拷贝
        BeanUtils.copyProperties(user,logininfo);
        if(user.getEmail()==null){
            logininfo.setDisable(true);
        }else {
            logininfo.setDisable(false);
        }
        logininfo.setType(1);//前台注册都是用户
        return logininfo;
    }

    /**
     * 将注册时的map集合，转换成user对象
     * @param map
     * @return
     */
    private User map2User(Map<String, String> map) {
        User user = new User();
        //手机注册
        if(map.get("email") == null){
            String phone = map.get("phone");
            user.setUsername(phone);
            user.setPhone(phone);
            user.setState(1);//手机注册默认启用
        }else {
            //邮箱注册
            String email = map.get("email");
            user.setUsername(email);
            user.setEmail(email);
            user.setState(0);//手机注册默认禁用
        }
        String password = map.get("password");
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
